package com.yunban.project.api.text_check.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.domain.TempCorrectRecord;
import com.yunban.project.api.text_check.dto.TestCorrectReq;
import com.yunban.project.api.text_check.dto.deepseek.ChatReq;
import com.yunban.project.api.text_check.dto.deepseek.enums.DeepSeekModel;
import com.yunban.project.api.text_check.enums.CorrectionModel;
import com.yunban.project.api.text_check.mapper.TempCorrectRecordMapper;
import com.yunban.project.api.text_check.service.CorrectionConfigService;
import com.yunban.project.api.text_check.service.DeepSeekService;
import com.yunban.project.api.text_check.service.TempCorrectRecordService;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.CompletableFuture;

/**
 * @author: lijiajun
 * @date: 2025-03-13
 * @version: 1.0
 */
@Service
public class TempCorrectRecordServiceImpl extends ServiceImpl<TempCorrectRecordMapper, TempCorrectRecord> implements TempCorrectRecordService {

    @Resource
    private DeepSeekService deepSeekService;

    @Resource
    private CorrectionConfigService correctionConfigService;

    @Override
    public String saveRecord(TestCorrectReq req) {
        TempCorrectRecord tempCorrectRecord = new TempCorrectRecord();
        tempCorrectRecord.setText(req.getText());
        tempCorrectRecord.setPrompt(req.getPrompt());
        this.save(tempCorrectRecord);
        // 调用ai
        // 调用异步方法并立即返回任务ID
        CompletableFuture.runAsync(() -> this.runAiMode(tempCorrectRecord.getTaskId(), req));
        return tempCorrectRecord.getTaskId();
    }

    @Override
    @Async
    public void runAiMode(String taskId, TestCorrectReq req) {
        CorrectionConfig config1 = this.correctionConfigService.findByCode(CorrectionModel.HUO_SHAN);
        if (StringUtils.hasText(req.getPrompt())) {
            config1.setPromptPrefix(req.getPrompt());
        }
        String result = null;
        try {
            ChatReq chatReq = new ChatReq();
            chatReq.setModel(DeepSeekModel.DEEPSEEK_V3.getModel());
            chatReq.setMessage(req.getText());
            result = deepSeekService.chat(chatReq);
        } catch (Exception ex) {
            result = ex.getMessage();
        }
        TempCorrectRecord record = this.getById(taskId);
        record.setResult(result);
        record.setFinished(true);
        this.updateById(record);
    }

    @Override
    public TempCorrectRecord findByTaskId(String taskId) {
        return this.getById(taskId);
    }
}
